import Components from "./Components.js";

export default class List extends Components {
    constructor(options) {
        super()
        this.wrapEl = options.wrapEl;
        List.todoData = options.todoData;
    }

    render() {
        this.wrapEl.innerHTML += Components.ListView(List.todoData)
    }

    bindEvent() {
        const oTodoList = document.querySelector('.todo-list')
        oTodoList.addEventListener('click', handleListClick.bind(this), false)
    }
}

List.addItem = function (val) {
    const item = {
        id: new Date().getTime(),
        content: val,
        completed: false
    }
    List.todoData.push(item)
    document.querySelector('.todo-list').innerHTML += Components.TodoView(item)
}

function handleListClick(e) {
    const tar = e.target
    const tagName = tar.tagName.toLowerCase();
    const oTodoItems = document.getElementsByClassName('todo-item')
    if (tagName === 'input' || tagName === 'button') {
        const id = parseInt(tar.dataset.id)
        switch (tagName) {
            case 'input':
                handleCheckBoxClick(id, oTodoItems)
                break;

            case 'button':
                handleButtonClick(id,oTodoItems)
                break;

            default:
                break;
        }
    }
}

function handleCheckBoxClick(id, oTodoItems) {
    List.todoData = List.todoData.map((todo, index) => {
        if (todo.id === id) {
            todo.completed = !todo.completed
            oTodoItems[index].querySelector('span').style.textDecoration = todo.completed ? 'line-through' : ''
        }
        return todo
    })
}

function handleButtonClick(id,oTodoItems) {
    List.todoData = List.todoData.filter((todo, index) => {
        if (todo.id !== id) {
            return todo
        } else {
            oTodoItems[index].remove()
        }
    })
}